CSS Scroll-Snap支援度:Can I Use)
以往寫slide都需額外利用第三方slide套件才能同時達到smooth和觸控滑動效果,前兩天學了scroll-behavior
和scroll-snap
,想說來試試看不用套件能不能一樣有觸控滑動的效果!
template
<div id="app">
<div class="container">
<ul class="slides">
<li class="slide" id="slide1">
<img src="https://picsum.photos/id/237/500/300" alt="">
</li>
<li class="slide" id="slide2">
<img src="https://picsum.photos/id/238/500/300" alt="">
</li>
<li class="slide" id="slide3">
<img src="https://picsum.photos/id/239/500/300" alt="">
</li>
<li class="slide" id="slide4">
<img src="https://picsum.photos/id/240/500/300" alt="">
</li>
<li class="slide" id="slide5">
<img src="https://picsum.photos/id/241/500/300" alt="">
</li>
</ul>
<a href="#" class="arrow arrow_left"></a>
<a href="#" class="arrow arrow_right"></a>
<div class="dots">
<a class="dot" href="#slide1"></a>
<a class="dot" href="#slide2"></a>
<a class="dot" href="#slide3"></a>
<a class="dot" href="#slide4"></a>
<a class="dot" href="#slide5"></a>
</div>
</div>
</div>
style
.container{
position:relative;
width:500px;
height:300px;
overflow:hidden;
}
.slides{
overflow-x:scroll;
scroll-behavior:smooth;
scroll-snap-type:x mandatory;
display:flex;
flex-direction:row;
}
.slide{
width:500px;
height:300px;
flex-shrink:0;
scroll-snap-align:start;
scroll-snap-stop:always;
overflow:hidden;
}
.dots{
position:absolute;
bottom:10px;
left:50%;
transform:translateX(-50%);
display:flex;
gap:10px;
}
.dot{
width:10px;
height:10px;
border-radius:50%;
background-color:white;
}